import json
import os
import shutil


def is_non_empty_directory(path):
    """检查给定路径是否为一个非空目录"""
    return os.path.isdir(path) and os.listdir(path)


def delete_directory(path):
    """删除给定路径的非空目录"""
    if is_non_empty_directory(path):
        try:
            shutil.rmtree(path)
            print(f"目录 {path} 已成功删除。")
        except Exception as e:
            print(f"删除目录 {path} 时发生错误: {e}")
    else:
        print(f"路径 {path} 不是一个非空目录。")

    # 打开 JSON 文件并读取数据


with open('./generate-deploy-const.json',
          'r',
          encoding='utf-8'
          ) as json_file:
    data = json.load(json_file)

# 读取项目名称
PROJECT_NAME = data['project_name']
project_dir = os.path.join(PROJECT_NAME)
# 判断脚本目录是否存在?如果存在则删除,如果不存在则创建,如果存在子文件,递归删除
if os.path.exists(project_dir):
    delete_directory(project_dir)
    print(f'{project_dir}项目存在,已将原始目录删除成功')

# 创建项目脚本目录
os.mkdir(project_dir)
if not os.path.exists(project_dir):
    print(f'{project_dir}项目创建成功')

# 写入项目控制常量的 常量文件名 const.json
const_file_path = project_dir + '/' + data['const']['const_file']
base_const_file = project_dir + '/' + data['const']['base_const_file']
with open(const_file_path,
          'w',
          encoding='utf-8'
          ) as f:
    json.dump(data['server_config'],
              f,
              ensure_ascii=False,
              indent=4
              )
    f.close()
    print(f'{const_file_path} 服务器相关信息写入成功')

with open(base_const_file,
          'w',
          encoding='utf-8'
          ) as f:
    json.dump(data['const'],
              f,
              ensure_ascii=False,
              indent=4
              )
    f.close()
    print(f'{const_file_path} 本地配置文件写入成功')

# 遍历 server_config
for server_name in data['server_config']:
    template = f'''
# {data['server_config'][server_name]['env_cname']}
import webbrowser
import json
import paramiko
import os
import subprocess
from script import *\n

remote_server='{server_name}'

with open('./base_const_file.json', 'r', encoding='utf-8') as base_json_file:
    base_const = json.load(base_json_file)
    
with open('./const.json', 'r', encoding='utf-8') as json_file:
    data = json.load(json_file)

# 读取配置数据
remote_server = data[remote_server]
work_dir = '{data['const']['local_web_path']}'
local_jar_path = base_const{['local_web_path']} + '/' + remote_server['dist_name']
remote_jar_path = remote_server['remote_jar_path']
os.chdir(work_dir)
process = subprocess.run(remote_server['command'],shell=True, stdout=subprocess.PIPE,  stderr=subprocess.PIPE,  universal_newlines=True)
if remote_server['pkey'] != 'None':
    private_key = paramiko.RSAKey.from_private_key_file(remote_server['pkey'])
else:
    private_key = None
               
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(remote_server['host'], remote_server['port'], remote_server['username'], password=remote_server['password'],pkey=private_key)
sftp = ssh.open_sftp()
               
# 上传
upload_dir(sftp, local_jar_path, remote_jar_path)
               
# 释放
sftp.close()
ssh.close()
               
#打开地址
webbrowser.open_new(remote_server['web_url'])

print('deploy complete!')
    '''
    with open(f"{project_dir}/{data['server_config'][server_name]['file_name']}",
              'w',
              encoding='utf-8'
              ) as f:
        f.write(template)
        f.close()

with open(f"{project_dir}/script.py",
          'w',
          encoding='utf-8'
          ) as f:
    f.write(f'''

import os

def clear_remote_dir(sftp, remote_dir):
    print('正在删除远程目录')
    try:
        files = sftp.listdir(remote_dir)
        for file in files:
            file_path = os.path.join(remote_dir, file)
            try:
                sftp.remove(file_path)
                print(f'已删除文件')
            except IOError:
                clear_remote_dir(sftp, file_path)
                sftp.rmdir(file_path)
    except FileNotFoundError:
        sftp.mkdir(remote_dir)


def upload_dir(sftp, local_dir, remote_dir):
    # 清空远程目录中的所有文件和子目录
    clear_remote_dir(sftp, remote_dir)
    print('正在上传文件到服务器...')
    for item in os.listdir(local_dir):
        local_path = os.path.join(local_dir, item)
        remote_path = os.path.join(remote_dir, item)

        if os.path.isdir(local_path):
            upload_dir(sftp, local_path, remote_path)
        else:
            sftp.put(local_path, remote_path)
            
    '''
            )
    f.close()
